import {
  getProfileAPI,
  getUserInfoAPI,
  loginAPI,
  sendCodeAPI,
  updateProfileAPI,
  uploadPhotoAPI,
} from '@/api/user';
import { setAuth } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import { AppDispatch } from '..';
import { ActionType, IProfile } from '@/store/reducer/user';
export const sendCodeAction = (mobile: string) => {
  return async () => {
    await sendCodeAPI(mobile);
  };
};

export const loginAction = (mobile: string, code: string) => {
  return async () => {
    const res = await loginAPI(mobile, code);
    setAuth(res.data);
    Toast.show('登录成功');
  };
};

export const getUserInfoAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserInfoAPI();
    dispatch({ type: 'user/saveUserInfo', payload: res.data });
  };
};

export const getProfileAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getProfileAPI();
    dispatch({ type: 'user/saveProfile', payload: res.data });
  };
};

export const uploadPhotoAction = (formData: FormData) => {
  return async () => {
    await uploadPhotoAPI(formData);
  };
};

export const updateProfileAction = (profile: Partial<IProfile>) => {
  return async () => {
    await updateProfileAPI(profile);
  };
};

export const clearInfoAction = (): ActionType => ({
  type: 'user/clearInfo',
});
